package br.com.pheat.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import br.com.pheat.beans.Usuario;
import br.com.pheat.dao.UsuarioDAO;

public class UsuarioRegistrarServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
       
    public UsuarioRegistrarServlet() {
        super();
    }

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		tratarRequisicao(request, response);
	}
	
	protected void tratarRequisicao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html");
		try{			
			String nome = request.getParameter("nome");
			String login = request.getParameter("login");
			String senha = request.getParameter("senha");

			float altura = 0;
			if(!request.getParameter("altura").equals(""))
				altura = Float.parseFloat(request.getParameter("altura"));

			float peso = 0;
			if(!request.getParameter("peso").equals(""))
				peso = Float.parseFloat(request.getParameter("peso"));

			float calorias = 2000;
			if(!request.getParameter("calorias").equals(""))			
				calorias = Float.parseFloat(request.getParameter("calorias"));

			String email = request.getParameter("email");

			Usuario usuario = new Usuario(nome, login.toLowerCase(), senha, altura, peso, calorias, email.toLowerCase());

			if(!UsuarioDAO.existeLogin(usuario.getLogin())){
				UsuarioDAO dao = new UsuarioDAO();
				dao.inserirUsuario(usuario);
				response.sendRedirect("index.jsp?m=c");
			}else{			
		    	request.setAttribute("dados", usuario);
				RequestDispatcher dispatcher = request.getRequestDispatcher("registrar.jsp?m=e");
				dispatcher.forward(request, response);
			}
		}catch(Exception e){
			response.sendRedirect("erro.jsp");
		}
	}
}